import config
from api.woocommerce import WooCommerce

class GoodsSync:
    def __init__(self):
        self.woocommerce()
        self.get_list()
    
    def woocommerce(self):
        self.api = WooCommerce()

    def get_list(self):
        # 载入缓存
        self.list = config.get('goods_sync')

    def handle_goods(self, list):
        data = []

        for item in list:
            # 检查更新时间
            if self.list.get(item['id'], None) != item['warehouse']:
                # 加入需要更新的sku列表中
                data.append(item)   

        return data

    def check(self, list, callback=None):
        data = []
        count = len(list)
        for index, item in enumerate(list):
            # 按 sku 查找商品
            callback(index, item, count)
            response = self.api.get_goods(item['sn'])
            # 如果存在就记录下来
            if response is not None:
                # 检查库存是否一致
                if response['stock_quantity'] != item['warehouse']:
                    data.append({
                        "id": response['id'],
                        "stock_quantity": item['warehouse']
                    })
        return data
    
    def sync(self, list):
        if len(list) > 0:
            return self.api.batch_goods(list)
        
        return True

    def update(self, list):
        # 更新缓存
        for item in list:
            self.list[item['id']] = item['warehouse']

        # 保存更新
        config.set('goods_sync', self.list)
    
    def empty(self):
        self.list = {}
        config.set('goods_sync', self.list)